class Solution:
    def countOfAtoms(self, formula: str) -> str:
        ele = ''
        low = ''
        stack = [1]
        num = ''
        counter = {}
        for i in range(len(formula) - 1, -1, -1):
            ele = formula[i] + low
            if ele.isdigit():
                num = ele + num
                continue
            elif ele.islower():
                low = ele + low
                continue
            elif ele == ')':
                n = 1 if num == '' else int(num)
                stack.append(stack[-1] * n)
                num = ''
                continue
            elif ele == '(':
                stack.pop()
                continue
            low = ''
            if ele not in counter:
                counter[ele] = 0
            if len(num) > 0:
                counter[ele] += int(num) * stack[-1]
            else:
                counter[ele] += stack[-1]
            num = ''
        res = ''
        for key in sorted(counter.keys()):
            c = ''
            if counter[key] > 1:
                c = str(counter[key])
            res += (key + c)
        return res
